package com.cloud.configure;

import com.cloud.common.constants.GlobalConstants;
import com.cloud.utils.MockRequestUtils;
import com.cloud.utils.ServletUtils;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * Feign 配置
 * 使用FeignClient 进行服务间调用,传递headers信息
 *
 * @author yzj
 */
@Configuration
public class FeignConfiguration implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
        HttpServletRequest request = null;
        ServletRequestAttributes attributes = ServletUtils.getRequestAttributes();
        // TODO 在非Web请求获取ServletRequestAttributes对象为null,需要重新设置对象
        if (ObjectUtils.isNotEmpty(attributes)) {
            request = attributes.getRequest();
        } else {
            // TODO 如果为空则判断定时任务/子线程请求设置授权免登账户
            request = MockRequestUtils.getRequest();
        }
        // 添加认证请求头
        requestTemplate.header(GlobalConstants.userId, request.getHeader(GlobalConstants.userId));
        requestTemplate.header(GlobalConstants.userName, request.getHeader(GlobalConstants.userName));
        requestTemplate.header(GlobalConstants.deptId, request.getHeader(GlobalConstants.deptId));
        requestTemplate.header(GlobalConstants.tokenKey, request.getHeader(GlobalConstants.tokenKey));
        requestTemplate.header(GlobalConstants.appTokenHeader, request.getHeader(GlobalConstants.appTokenHeader));
        requestTemplate.header(GlobalConstants.tokenHeader, request.getHeader(GlobalConstants.tokenHeader));
    }

}
